import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Radio, Space } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import { proShiftTeamUserPage } from '@/services/bizApi/shengchanbanzurenyuanjiekou';
import { proRunLogAdd, proRunLogUpdate } from '@/services/bizApi/shengchanyunxingrizhijiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';
import styles from './index.module.scss';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const teamArray = useRef<BIZAPI.ProShiftTeamEntity[]>([]);
  const [userData, setUserData] = useState<BIZAPI.ProShiftTeamUserEntity[]>([]);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        dates: values?.dates ? dayjs(values?.dates).format('YYYY-MM-DD') : undefined,
        teamName: teamArray.current.find((item) => item.id === values.teamId)?.name,
        successorName: userData.find((item) => item.userId === values.successorId)?.userName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? proRunLogUpdate(query) : proRunLogAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            const dates = dayjs(arg.rowData.dates);
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              dates
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增交接班',
          edit: '编辑交接班',
          detail: '交接班详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="70%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        requiredMark={args?.type !== 'detail'}
        disabled={args?.type === 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="日期"
          name="dates"
          rules={[
            {
              required: true,
              message: '请选择日期'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="请选择日期" />
        </Form.Item>
        <ProFormSelect
          name="teamId"
          label="班组名称"
          placeholder="请选择班组名称"
          rules={[{ required: true, message: '请选择班组名称' }]}
          request={async () => {
            const res = await proShiftTeamPage({
              page: 1,
              size: 1000
            });
            teamArray.current = res.data?.records || [];

            return (
              res.data?.records?.map((item) => ({
                value: item.id,
                label: item.name
              })) || []
            );
          }}
          onChange={(value) => {
            form.setFieldsValue({
              successorId: undefined
            });
          }}
        />
        <ProFormSelect
          name="successorId"
          label="接班人"
          placeholder="请选择接班人"
          dependencies={['teamId']}
          rules={[{ required: true, message: '请选择接班人' }]}
          request={async () => {
            const res = await proShiftTeamUserPage({
              teamId: form.getFieldValue('teamId'),
              page: 1,
              size: 1000
            });
            setUserData(res?.data?.records || []);
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.userName,
                  value: item?.userId
                };
              }) || []
            );
          }}
        />

        {/* <Form.Item
          label="设备问题"
          name="equipmentIssues"
          rules={[
            {
              required: false,
              message: '请输入设备问题'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入设备问题" />
        </Form.Item> */}

        {args?.type === 'detail' && (
          <>
            <Form.Item
              label="是否异常"
              name="hasIssue"
              rules={[
                {
                  required: false,
                  message: '请选择是否异常'
                }
              ]}
            >
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="是否有接班注意事项"
              name="hasNotice"
              rules={[
                {
                  required: false,
                  message: '请选择是否有接班注意事项'
                }
              ]}
            >
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
          </>
        )}

        <div>
          <div className={styles['title']}>
            <div className={styles['title-title']}>工段</div>
            <div className={styles['title-content']}>生产运行情况</div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>预处理</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>气浮设备</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r1Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r1Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r1Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>生化工段</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>生化</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r2Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r2Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r2Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>MBR</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>MBR</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r3Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r3Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r3Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>深度处理</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>芬顿及BAF</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r4Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r4Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r4Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>脱离工段</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>离心机</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r5Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r5Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r5Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          <div className={styles['item']}>
            <div className={styles['item-title']}>外排水</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>外排</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>运行情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r6Status"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>异常情况&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r6Issue"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
                <div className={styles['item-value-right-top']}>
                  <div className={styles['item-value-right-top-title']}>接班注意事项&nbsp;</div>
                  <Form.Item
                    noStyle
                    label=""
                    name="r6Notice"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 4 }}
                      placeholder="请输入"
                      style={{ width: '500px' }}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div>
          {/* <div className={styles['item']}>
            <div className={styles['item-title']}>委外作业</div>
            <div className={styles['item-value']}>
              <div className={styles['item-value-left']}>安全监管</div>
              <div className={styles['item-value-right']}>
                <div className={styles['item-value-right-top']}>
                  <Form.Item
                    noStyle
                    label=""
                    name="outsourcingDesc"
                    rules={[
                      {
                        required: false,
                        message: '请输入'
                      }
                    ]}
                  >
                    <Input.TextArea placeholder="请输入" style={{ width: '500px' }} />
                  </Form.Item>
                </div>
              </div>
            </div>
          </div> */}
        </div>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
